package com.thiswhyme.common.utils.json.gson.typeadapter;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @description: LocalDateTime序列化器
 * @author: thiswhyme
 * @date: 2020/9/17
 */
public class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {

    public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private String dateFormat;

    /**
     * 默认构造器
     */
    public LocalDateTimeSerializer() {
        this(DEFAULT_PATTERN);
    }

    /**
     * 指定格式的构造函数
     * @param dateFormat
     */
    public LocalDateTimeSerializer(String dateFormat) {
        super();
        this.dateFormat = dateFormat;
    }

    public String getDateFormat() {
        return this.dateFormat;
    }

    private DateTimeFormatter formatter() {
        return DateTimeFormatter.ofPattern(this.dateFormat);
    }

    @Override
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return null == json ? null : LocalDateTime.parse(json.getAsString(), formatter());
    }

    @Override
    public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
        return  null == src ? null : new JsonPrimitive(formatter().format(src));
    }
}
